﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GiaPhuc;
using System.IO;
using GiaPhuc.Data;
using System.Data;
using GiaPhuc.Model;

public partial class Pages_ProductEntry : System.Web.UI.Page
{
    private int ProductID
    {
        get
        {
            if (null != Request["ID"])
            {
                return int.Parse(Request["ID"]);
            }
            return 0;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadCategories();

            using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.ConnectionString))
            {
                using (ResellEraDMInPhUkIeNipAdX context = new ResellEraDMInPhUkIeNipAdX(connection))
                {

                    int productID = ProductID;
                    Products product = context.Products.SingleOrDefault(x => x.ProductsID == productID);

                    if (null != product)
                    {
                        this.txtPrice.Text = product.ProductsPrice.ToString();
                        this.imgProduct.ImageUrl = product.ProductsImage;
                        this.ddlCategory.SelectedValue = product.MasterCategoriesID.ToString();
                        this.chkIsCall.Checked = Convert.ToBoolean(product.ProductIsCall);
                        this.chkDeactive.Checked = !Convert.ToBoolean(product.ProductsStatus);
                        this.chkIsNew.Checked = Convert.ToBoolean(product.ProductIsFree);
                        this.chkIsHot.Checked = Convert.ToBoolean(product.ProductIsAlwaysFreeShipping);

                        ProductsDescription description = context.ProductsDescription.SingleOrDefault(x => x.ProductsID == productID);

                        this.txtProductName.Text = description.ProductsName;
                        this.txtProducts_Images.Text = description.ProductsImages.RemoveBadCode();
                        this.txtProducts_Description.Text = description.ProductsDescription1.RemoveBadCode();
                    }
                }
            }
        }
    }

    protected void lnkSave_Click(object sender, EventArgs e)
    {
        try
        {
            using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.ConnectionString))
            {
                using (ResellEraDMInPhUkIeNipAdX context = new ResellEraDMInPhUkIeNipAdX(connection))
                {
                    if (uplProductImage.HasFile)
                    {
                        string path = Server.MapPath(String.Concat(define.UPLOAD_FOLDER, uplProductImage.FileName));
                        path = path.Replace('\\', '/');

                        using (Stream outFile = System.IO.File.OpenWrite(path))
                        {
                            CopyStream(uplProductImage.FileContent, outFile);
                        }
                    }

                    if (ProductID == 0)
                    {
                        Products product = new Products
                        {
                            ProductsPrice = decimal.Parse(this.txtPrice.Text),
                            MasterCategoriesID = int.Parse(this.ddlCategory.SelectedValue),
                            ProductIsCall = Convert.ToSByte(this.chkIsCall.Checked),
                            // IsNew & IsHot
                            ProductIsFree = Convert.ToSByte(this.chkIsNew.Checked),
                            ProductIsAlwaysFreeShipping = Convert.ToSByte(this.chkIsHot.Checked),
                            ProductsStatus = Convert.ToSByte(!this.chkDeactive.Checked)
                        };

                        if (uplProductImage.HasFile)
                        {
                            product.ProductsImage = String.Concat(define.UPLOAD_FOLDER, uplProductImage.FileName);
                        }

                        context.Products.InsertOnSubmit(product);

                        context.SubmitChanges();

                        ProductsDescription description = new ProductsDescription
                        {
                            ProductsID = product.ProductsID,
                            ProductsName = this.txtProductName.Text,
                            ProductsImages = this.txtProducts_Images.Text,
                            ProductsDescription1 = this.txtProducts_Description.Text
                        };
                        context.ProductsDescription.InsertOnSubmit(description);
                    }
                    else
                    {
                        int productID = ProductID;
                        Products product = context.Products.SingleOrDefault(x => x.ProductsID == productID);

                        product.ProductsStatus = Convert.ToSByte(!this.chkDeactive.Checked);
                        product.ProductIsCall = Convert.ToSByte(this.chkIsCall.Checked);

                        // IsNew & IsHot
                        product.ProductIsFree = Convert.ToSByte(this.chkIsNew.Checked);
                        product.ProductIsAlwaysFreeShipping = Convert.ToSByte(this.chkIsHot.Checked);

                        product.ProductsPrice = decimal.Parse(this.txtPrice.Text);
                        if (uplProductImage.HasFile)
                        {
                            product.ProductsImage = String.Concat(define.UPLOAD_FOLDER, uplProductImage.FileName);
                        }
                        product.MasterCategoriesID = int.Parse(this.ddlCategory.SelectedValue);

                        ProductsDescription description = context.ProductsDescription.SingleOrDefault(x => x.ProductsID == productID);

                        description.ProductsName = this.txtProductName.Text;
                        description.ProductsImages = this.txtProducts_Images.Text;
                        description.ProductsDescription1 = this.txtProducts_Description.Text;
                    }

                    context.SubmitChanges();
                }
            }

            if (ProductID == 0)
            {
                Response.Redirect("/Admin/Pages/ProductEntry.aspx");
            }
            else
            {
                Response.Redirect("/Admin/Pages/ProductManager.aspx");
            }
        }
        catch
        {
            throw;
        }
    }

    #region Private Methods
    /// <summary> 
    /// Copies the contents of input to output. Doesn't close either stream. 
    /// </summary> 
    private void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[8 * 1024];
        int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    }

    private void LoadCategories()
    {
        using (IDbConnection connection = new MySql.Data.MySqlClient.MySqlConnection(Helper.ConnectionString))
        {
            using (ResellEraDMInPhUkIeNipAdX context = new ResellEraDMInPhUkIeNipAdX(connection))
            {
                var collection = from x in context.Categories.ToList()
                                 join y in context.CategoriesDescription
                                 on x.CategoriesID equals y.CategoriesID
                                 orderby x.SortOrder
                                 select new { x, y };

                IList<CategoryModel> categories = new List<CategoryModel>();
                if (collection.Count() > 0)
                {
                    foreach (var item in collection)
                    {
                        categories.Add(new CategoryModel
                        {
                            CategoryID = item.x.CategoriesID,
                            CategoryName = item.y.CategoriesName
                        });
                    }

                    this.ddlCategory.DataSource = categories;
                    this.ddlCategory.DataValueField = "CategoryID";
                    this.ddlCategory.DataTextField = "CategoryName";
                    this.ddlCategory.DataBind();
                }
                else
                {
                    context.Categories.DeleteAllOnSubmit(context.Categories);
                    context.CategoriesDescription.DeleteAllOnSubmit(context.CategoriesDescription);

                    context.Categories.InsertOnSubmit(new Categories
                    {
                        CategoriesID = 1,
                        DateAdded = DateTime.Now,
                        SortOrder = 1
                    });

                    context.Categories.InsertOnSubmit(new Categories
                    {
                        CategoriesID = 2,
                        DateAdded = DateTime.Now,
                        SortOrder = 2
                    });

                    context.Categories.InsertOnSubmit(new Categories
                    {
                        CategoriesID = 3,
                        DateAdded = DateTime.Now,
                        SortOrder = 3
                    });

                    context.Categories.InsertOnSubmit(new Categories
                    {
                        CategoriesID = 4,
                        DateAdded = DateTime.Now,
                        SortOrder = 4
                    });

                    context.Categories.InsertOnSubmit(new Categories
                    {
                        CategoriesID = 5,
                        DateAdded = DateTime.Now,
                        SortOrder = 5
                    });

                    context.Categories.InsertOnSubmit(new Categories
                    {
                        CategoriesID = 6,
                        DateAdded = DateTime.Now,
                        SortOrder = 6
                    });

                    context.CategoriesDescription.InsertOnSubmit(new CategoriesDescription
                    {
                        CategoriesID = 1,
                        CategoriesName = "Pin dự phòng",
                        CategoriesDescription1 = String.Empty
                    });

                    context.CategoriesDescription.InsertOnSubmit(new CategoriesDescription
                    {
                        CategoriesID = 2,
                        CategoriesName = "Bluetooth keyboard",
                        CategoriesDescription1 = String.Empty
                    });

                    context.CategoriesDescription.InsertOnSubmit(new CategoriesDescription
                    {
                        CategoriesID = 3,
                        CategoriesName = "Tai nghe bluetooth",
                        CategoriesDescription1 = String.Empty
                    });

                    context.CategoriesDescription.InsertOnSubmit(new CategoriesDescription
                    {
                        CategoriesID = 4,
                        CategoriesName = "Bao da Ipad",
                        CategoriesDescription1 = String.Empty
                    });

                    context.CategoriesDescription.InsertOnSubmit(new CategoriesDescription
                    {
                        CategoriesID = 5,
                        CategoriesName = "Case Iphone",
                        CategoriesDescription1 = String.Empty
                    });

                    context.CategoriesDescription.InsertOnSubmit(new CategoriesDescription
                    {
                        CategoriesID = 6,
                        CategoriesName = "Cáp, tai nghe & sạc Iphone",
                        CategoriesDescription1 = String.Empty
                    });

                    context.SubmitChanges();
                }
            }
        }
    }
    #endregion

}